package com.gitee.easyopen;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.gitee.easyopen.message.Errors;
import com.gitee.easyopen.util.RequestUtil;

public class ApiParamParser implements ParamParser {

    private static final Logger logger = LoggerFactory.getLogger(ApiParamParser.class);

    @Override
    public ApiParam parse(HttpServletRequest request) {
        String requestJson = "";
        boolean encryptMode = ApiContext.isEncryptMode();
        
        try {
            requestJson = RequestUtil.getJson(request);
            
            if (encryptMode) {
                String randomKey = ApiContext.getRandomKey();
                if (randomKey == null) {
                    logger.error("未找到randomKey");
                    throw Errors.ERROR_SSL.getException();
                }
                requestJson = ApiContext.decryptAES(requestJson);
            }
            return this.jsonToApiParam(requestJson);
        } catch (Exception e) {
            logger.error("不合法的参数", e);
            throw Errors.ERROR_SSL.getException();
        }
    }
    
    protected ApiParam jsonToApiParam(String json) {
        if (StringUtils.isEmpty(json)) {
            throw Errors.ERROR_PARAM.getException();
        }

        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(json);
        } catch (Exception e) {
            throw Errors.ERROR_JSON_DATA.getException(e.getMessage());
        }

        return new ApiParam(jsonObject);
    }

}
